<template>
  <div class="manage">
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handelClose">
      <!--新增表单信息 -->
      <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="roleName" >
          <el-input placeholder="请输入角色名称" v-model="form.roleName" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" placeholder="请输入备注" v-model="form.remark" :disabled="disabled"></el-input>
        </el-form-item>
        <br/>
        <div v-show="show">
          <el-card shadow="never">
            <el-form-item label="部门">
              <!--<el-tree :data="deptList" :props="deptDefaultProps" @node-click="handleNodeClick"></el-tree>-->
              <el-tree
                :data="deptList"
                show-checkbox
                node-key="deptId"
                :default-expanded-keys="defaultDeptIds"
                :default-checked-keys="defaultDeptIds"
                @check="handleNodeDeptClick"
                :props="deptDefaultProps">
              </el-tree>
            </el-form-item>
            <el-form-item label="菜单">
              <el-tree
                :data="menuList"
                show-checkbox
                node-key="menuId"
                :default-expanded-keys="defaultMenuIds"
                :default-checked-keys="defaultMenuIds"
                @check="handleNodeMenuClick"
                :props="menuDefaultProps">
              </el-tree>
            </el-form-item>
          </el-card>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <div class="manage-header">
      <el-button @click="handelAdd" type="primary">
        <i class="el-icon-plus"></i>新增
      </el-button>
      <!--form 搜索区-->
      <el-form :inline="true" :model="form">
        <el-form-item>
          <el-input placeholder="请输入姓名" v-model="userForm.roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="dateTime"
            value-format="yyyy/MM/dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-table">
      <!--内容-->
      <el-table
        height="90%"
        :data="tableData"
        style="width: 100%"
        stripe>
        <el-table-column type="index" label="序号" fixed></el-table-column>
        <el-table-column prop="roleName" label="角色名称" fixed></el-table-column>
        <el-table-column prop="" label="状态" width="100">
          <template slot-scope="scope">
            <a @click="updateDelFlag(scope.row)">
              <el-switch
                v-model="scope.row.delFlag==0 ? true : false"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </a>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          width="170"
          label="创建时间">
        </el-table-column>
        <el-table-column prop="remark" label="备注" fixed></el-table-column>
        <el-table-column prop="" label="操作" width="165" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handelEditRole(scope.row)"><i class="el-icon-edit"></i>修改</el-button>
            <el-button type="text" size="mini" @click="handelDelRole(scope.row)"><i class="el-icon-delete"></i>删除</el-button>
            <el-tooltip placement="bottom" effect="light">
              <div slot="content">
                <el-button type="text" size="mini" @click="handelDataRole(scope.row)"><i class="el-icon-circle-check"></i>数据权限</el-button>
              </div>
              <el-button type="text" size="mini"><i class="el-icon-d-arrow-right"></i>更多</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--页码-->
      <div class="pager">
        <el-pagination
          layout="prev, pager, next"
          :total="this.total"
          @current-change="handelPage">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
    import { listPageRole, saveOrUpdateRole, delRole, listDeptTree, editRoleAndDeptIdAndMenuId , listMenuTree, updateById} from "../api"
    export default {
        name: "Role",
        data(){
            return{
                dialogVisible:false,
                form: {
                    roleId: '',
                    roleName: '',
                    remark: '',
                    delFlag: '',
                    deptIds:[],
                    menuIds:[]
                },
                rules:{
                    roleName: [
                        {required: true,message: '请输入角色名'}
                    ],
                },
                tableData: [],
                modelType: 0,  //0：新增，1：修改
                total: 0,
                pageData:{
                    page: 1,
                    limit: 10
                },
                dateTime:[],
                //查询条件
                userForm: {
                    roleName: "",
                    startTime: '',
                    endTime: ''
                },
                deptList: [],
                defaultDeptIds:[],
                deptDefaultProps: {
                    label: 'deptName',
                    children: 'depts',
                    disabled: 'delFlag'
                },
                menuList: [],
                defaultMenuIds:[],
                menuDefaultProps: {
                    label: 'menuName',
                    children: 'menus',
                    disabled: 'delFlag'
                },
                show: false,
                disabled: false
            }
        },
        methods:{
            //获取选中与父级的id
            handleNodeDeptClick(data, checked) {
                //部门id
                //console.log(checked,"checked");
                //选中的
                const checkedKeys=checked.checkedKeys;
                //半选中的
                const halfCheckedKeys=checked.halfCheckedKeys;
                this.form.deptIds=checkedKeys.concat(halfCheckedKeys);
                //console.log(this.form.deptIds);
            },
            handleNodeMenuClick(data, checked) {
                //菜单id
                //console.log(checked,"checked");
                //选中的
                const checkedKeys=checked.checkedKeys;
                //半选中的
                const halfCheckedKeys=checked.halfCheckedKeys;
                this.form.menuIds=checkedKeys.concat(halfCheckedKeys)
            },
            //提交用户表单
            submit(){
                //进行校验
                this.$refs.form.validate((valid)=>{
                    if (valid){
                        if (this.modelType == 0){
                            //新增
                            this.form.id=null;
                            saveOrUpdateRole(this.form).then(({ data })=>{
                                this.$message({
                                    type: data.type,
                                    message: data.message
                                });
                                this.listPageRole();
                            });
                        }else{
                            //修改
                            saveOrUpdateRole(this.form).then(({ data }) => {
                                this.$message({
                                    type: data.type,
                                    message: data.message
                                });
                                this.listPageRole();
                            });
                        }
                        this.handelClose();
                    }
                });
            },
            //弹窗关闭的时候
            handelClose(){
                //重置表单
                this.$refs.form.resetFields();
                this.dialogVisible=false;
            },
            //点击取消
            cancel(){
                this.handelClose();
            },
            //编辑
            handelEditRole(row){
                this.disabled=false;
                this.show=false;
                this.modelType=1;
                this.dialogVisible=true;
                //查找出role的部门和菜单,并编辑
                this.editRoleAndDeptIdAndMenuId(row);
            },
            //查找出role的部门和菜单
            editRoleAndDeptIdAndMenuId(row){
                //需要对当前的数据进行深拷贝，否则会出错，不能直接this.form=row;
                this.form=JSON.parse(JSON.stringify(row));
                editRoleAndDeptIdAndMenuId(row).then(({data})=>{
                    this.listDeptTree();
                    this.listMenuTree();
                    //console.log(data);
                    this.form.deptIds=data.deptIds;
                    this.defaultDeptIds=data.deptIds;
                    this.form.menuIds=data.menuIds;
                    this.defaultMenuIds=data.menuIds;

                    if (this.form.deptIds==null){
                        this.form.deptIds=[];
                        this.defaultDeptIds=[];
                    }else{
                        this.funDept(this.deptList);
                    }
                    if (this.form.menuIds==null){
                        this.form.menuIds=[];
                        this.defaultMenuIds=[];
                    }else{
                        this.funMenu(this.menuList);
                    }
                });
            },
            //数据权限
            handelDataRole(row){
                this.disabled=true;
                this.show=true;
                this.modelType=1;
                this.dialogVisible=true;
                //查找出role的部门和菜单,并编辑
                this.editRoleAndDeptIdAndMenuId(row);
            },
            //递归删除部门的id
            funDept(item){
                if (item!=null){
                    item.forEach(itm=>{
                        if (itm.depts!=null){
                            //console.log(itm);
                            this.defaultDeptIds = this.defaultDeptIds.filter(it => it!=itm.deptId);
                            this.funDept(itm.depts);
                        }
                    });
                }
            },
            funMenu(item){
                if (item!=null){
                    item.forEach(itm=>{
                        if (itm.menus!=null){
                            this.defaultMenuIds = this.defaultMenuIds.filter(it => it!=itm.menuId);
                            this.funDept(itm.menus);
                        }
                    });
                }
            },
            //修改状态
            updateDelFlag(row){
                this.$confirm('确定要“'+(row.delFlag == 0 ? "停用" : "启用")+'”“'+row.roleName+'角色吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    row.delFlag=(row.delFlag == 0 ? 1 : 0);
                    //修改
                    updateById(row).then(({ data }) => {
                        this.listPageRole();
                    });
                    this.$message({
                        type: "success",
                        message: "修改成功"
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            //删除
            handelDelRole(row){
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delRole(row).then(({ data })=>{
                        this.listPageRole();
                    });
                    this.$message({
                        type: "success",
                        message: "删除成功"
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //新增
            handelAdd(){
                this.disabled=false;
                this.show=false;
                this.form={
                    roleId: '',
                    roleName: '',
                    remark: '',
                    delFlag: '',
                    deptIds:[],
                    menuIds:[]
                };
                this.modelType=0;
                this.dialogVisible=true;
            },
            //获取列表
            listPageRole(){
                listPageRole({...this.userForm,...this.pageData}).then(( {data} )=>{
                    //console.log(data,"获取的")
                    this.tableData=data.list;
                    //如果data.count不存在 就为0
                    this.total=data.count || 0;
                });
            },
            //获取部门列表
            listDeptTree(){
                listDeptTree().then(({data})=>{
                    this.deptList=data;
                });
            },
            //获取菜单列表
            listMenuTree(){
                listMenuTree().then(({data})=>{
                    this.menuList=data;
                });
            },
            //递归比遍历设置禁用
            /*disabledDept(item){
                if (item!=null){
                    item.forEach(itm=>{
                        if (itm.delFlag==1){
                            itm.disabled=true;
                        }
                        if (itm.depts!=null){
                            this.disabledDept(itm.depts);
                        }
                    });
                }
            },
            disabledMenu(item){
                if (item!=null){
                    item.forEach(itm=>{
                        if (itm.delFlag==1){
                            itm.disabled=true;
                        }
                        if (itm.menus!=null){
                            this.disabledMenu(itm.menus);
                        }
                    });
                }
            },*/
            //获取页码
            handelPage(val){
                //console.log(val);
                this.pageData.page=val;
                this.listPageRole();
            },
            //条件查询
            onSubmit(){
                if (this.dateTime!=null && this.dateTime.length>0 && this.dateTime!=null){
                    this.userForm.startTime=new Date(this.dateTime[0]).toLocaleDateString();
                    this.userForm.endTime=new Date(this.dateTime[1]).toLocaleDateString();
                }else{
                    this.userForm.startTime=null;
                    this.userForm.endTime=null;
                }
                this.listPageRole();
            }
        },
        //页面首次加载时调用的地方
        mounted() {
            this.listMenuTree();
            this.listPageRole();
            this.listDeptTree();
        }
    }
</script>

<style lang="less" scoped>
  .manage{
    height: 90%;
    .manage-header{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .common-table{
      position: relative;
      //动态计算高度
      height: calc(100% - 62px);
      .pager{
        position: absolute;
        bottom: 0;
        right: 20px;
      }
    }
  }
</style>
